﻿#include "Connection.h"
#include <QTimer>

namespace TC
{
    Connection::Connection(QObject *parent /*= nullptr*/) : QSslSocket(parent)
    {
        setSocketOption(QAbstractSocket::SocketOption::LowDelayOption, true);

        QObject::connect(this, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QSslSocket::error),
            this, &Connection::onSocketError);
    }

    void Connection::connectToHostEncrypted(const QString &hostName, quint16 port, OpenMode mode /*= ReadWrite*/, NetworkLayerProtocol protocol /*= AnyIPProtocol*/)
    {
        QSslSocket::connectToHostEncrypted(hostName, port, mode, protocol);
        QTimer::singleShot(3000, this, &Connection::onConnectTimeout);
    }

    void Connection::onConnectTimeout()
    {
        if (this->state() == QAbstractSocket::HostLookupState || this->state() == QAbstractSocket::ConnectingState)
        {
            qDebug() << "Connection::onConnectTimeout()->in";
            this->close();
            this->setSocketError(QAbstractSocket::SocketTimeoutError);
            this->setErrorString(QObject::tr("Timed-out when attempting to connect to server."));
            QAbstractSocket::error(QAbstractSocket::SocketTimeoutError);
        }
    }

    void Connection::onSocketError(QAbstractSocket::SocketError socketError)
    {
        Q_UNUSED(socketError);
        this->error(this->errorString());
    }

}
